package org.glut.AppStoreProject.controller;

import com.google.gson.Gson;
import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.glut.AppStoreProject.entity.AppEntity11;
import org.glut.AppStoreProject.service.AppService11;

import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 应用控制器，处理HTTP请求
 */
@WebServlet({"/apps"})
public class AppServlet11 extends HttpServlet {
    private AppService11 appService;
    private static final Gson gson = new Gson(); // 添加 Gson 实例
    @Override
    public void init() throws ServletException {
        appService = new AppService11();
    }

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        resp.setContentType("application/json;charset=UTF-8");

        resp.setHeader("Access-Control-Allow-Origin", "*");
        resp.setHeader("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS");
        resp.setHeader("Access-Control-Allow-Headers", "Content-Type");
        String appTypeParam = req.getParameter("appType");

        try {
            if (appTypeParam == null || appTypeParam.isEmpty()) {
                writeErrorResponse(resp, "必须提供appType参数");
                return;
            }

            int appType = Integer.parseInt(appTypeParam);
            List<AppEntity11> apps = appService.getAppsByAppType(appType);

            resp.getWriter().write(gson.toJson(apps));
        } catch (NumberFormatException e) {
            writeErrorResponse(resp, "appType参数必须是整数");
        } catch (Exception e) {
            e.printStackTrace();
            writeErrorResponse(resp, "查询失败");
        }
    }

    private void writeErrorResponse(HttpServletResponse resp, String message) throws IOException {
        Map<String, String> errorMap = new HashMap<>();
        errorMap.put("error", message);
        resp.getWriter().write(gson.toJson(errorMap));
    }
}
